#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>

#define BUF_SIZE 1024
#define PORT 8888
#define MGROUP "224.2.2.2"  //多播地址

int main(int argc,char **argv) {
    int client_socket;
    struct sockaddr_in server_addr;
    char buf[BUF_SIZE];
    if(argc != 2)
    {
    	fprintf(stderr,"Usage: ./%s message",argv[0]);
    } 

    // 创建UDP套接字并连接到服务器地址和端口
    client_socket = socket(AF_INET, SOCK_DGRAM, 0);
    if (client_socket < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
/*
    // 设置多播组	选项IP_MULTICAST_IF用于设置组播的默认默认网络接口，会从给定的网络接口发送，另一个网络接口会忽略此数据
    struct ip_mreqn mreq;
    inet_pton(AF_INET,MGROUP,&mreq.imr_multiaddr);
    inet_pton(AF_INET,"0.0.0.0",&mreq.imr_address);
    mreq.imr_ifindex = if_nametoindex("eth0");
    
    if (setsockopt(client_socket, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof(mreq)) < 0) {
        perror("setsockopt failed");
        exit(EXIT_FAILURE);
    }
*/
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = inet_addr(MGROUP); // 多播地址
    int len = sendto(client_socket, argv[1], strlen(argv[1]), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));

    // 关闭套接字并退出程序
    close(client_socket);
    return 0;
}
